﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections;
using personalplaner.gui.stamm.viewmodels;
using personalplaner.business.stamm;
using personalplaner.common.controls;

namespace personalplaner.gui.stamm.views
{
	/// <summary>
	/// Interaction logic for PlanLayoutStamm.xaml
	/// </summary>
	public partial class PlanLayoutStamm : BaseControl
	{
		public PlanLayoutStamm()
		{
			InitializeComponent();
		}

        public void SetSinglePlanSchema(int schemaid)
        {
            var dc = DataContext as PlanLayoutStammViewModel;
            if (dc == null)
                return;

            dc.SetSinglePlanSchema(schemaid);
        }

		private void LayoutList_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			var parent = (ListBox)sender;
			object data = GetDataFromListBox(parent, e.GetPosition(parent));

			if (data != null)
			{
				DragDrop.DoDragDrop(parent, data, DragDropEffects.Move);
			}
		}

		private void LayoutList_Drop(object sender, DragEventArgs e)
		{
			var parent = (ListBox)sender;
			var data = e.Data.GetData(typeof(PlanSchemaItem)) as PlanSchemaItem;
			if (data == null)
				return;


			object tmp = GetDataFromListBox(parent, e.GetPosition(parent));
			int i = ((IList)parent.ItemsSource).IndexOf(tmp);

			var dc = DataContext as PlanLayoutStammViewModel;
			if (dc == null)
				return;

			dc.ModeItemTo(data, i);
		}




		private static object GetDataFromListBox(ListBox source, Point point)
		{
			var element = source.InputHitTest(point) as UIElement;
			if (element != null)
			{
				object data = DependencyProperty.UnsetValue;
				while (data == DependencyProperty.UnsetValue)
				{
					data = source.ItemContainerGenerator.ItemFromContainer(element);
					if (data == DependencyProperty.UnsetValue)
					{
						element = VisualTreeHelper.GetParent(element) as UIElement;
					}
					if (element == source)
					{
						return null;
					}
				}
				if (data != DependencyProperty.UnsetValue)
				{
					return data;
				}
			}
			return null;
		}
	}
}
